package com.juyu.miliao.api.rabbitMQ;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.service.ChatSpendService;
import com.juyu.miliao.api.service.LineTimeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Optional;

@Component
public class LineTimeRabbitMQ {
    private final Logger logger = LoggerFactory.getLogger("lineTimeRabbitMQ");
    private final Logger loggerSignOut = LoggerFactory.getLogger("hostLineTimeSignOut");
    private final Logger loggerLogin = LoggerFactory.getLogger("hostLineTimeLogin");
    private final Logger loggerRoom = LoggerFactory.getLogger("chatSpendRoomId");
    @Resource
    LineTimeService lineTimeService;
    @Resource
    ChatSpendService chatSpendService;
    @Resource
    UserInfoDao userInfoDao;

    @RabbitListener(bindings = @QueueBinding(value = @Queue("queue_host_line_sign_out"),
            exchange = @Exchange("exchange_host_line_sign_out"),
            key = "routing_key_host_line_sign_out"))
    public void hostLineTimeSignOut(String accid){
        User user = userInfoDao.getUserInfoById(Long.parseLong(accid));
        if(user!=null){
            loggerSignOut.info("hostLineTimeSignOut主播登出操作同步,accid::::::"+accid
                    +",eventType::::::3");
            lineTimeService.countLineTime("3",accid, Instant.now().toEpochMilli()+"",user);
        }
    }

    /**
     * 同步登录请求
     */
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue("messagecc-2"),
//            exchange = @Exchange("xxx")
//    ))
    @RabbitListener(queues = "messagecc-2")
    public void lineTimeUserLogin(String json){
        lineTimeUtil(json,2);
    }

    /**
     * 同步登出请求
     */
    @RabbitListener(queues = "messagecc-3")
    public void lineTimeUserLogout(String json){
        lineTimeUtil(json,3);
    }

    /**
     * 音频时长消息抄送
     * @param json
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue("messagecc-5-queue"),
            exchange = @Exchange(value = "messagecc-5",type = ExchangeTypes.FANOUT)))
    public void chatSpendEndMessage(String json){
        loggerRoom.info("messagecc-5::::::"+json);
        chatSpendService.chatSpendEndByServer(json);
    }

    private void lineTimeUtil(String json,int type){
        try {
            if (json == null || json.isEmpty()) {
                if(logger.isInfoEnabled()){
                    logger.info("用户在线时长rabbitMQ抄送请求错误, json 为空!");
                }
                return;
            }
            logger.info("同步LineTimeRabbitMQ传递参数---{}",json);

            JSONObject jsStr = JSONObject.parseObject(json);
            //	登录事件的返回码，可转为Integer类型数据
            String code = jsStr.get("code").toString();
            if(!code.equals("200")){
                logger.error("lineTimeRabbitMQ处理错误:code!=200,json---{}", json);
                return;
            }
            //发生事件的用户帐号，字符串类型
            String accid = jsStr.get("accid").toString();
            // 	值为2，表示是登录事件的消息,	值为3，表示是登出事件的消息
            String eventType = jsStr.get("eventType").toString();
            //事件发生时的时间戳，可转为Long型数据
            String timestamp = jsStr.get("timestamp").toString();
            //登录时的ip地址
//            String clientIp = jsStr.get("clientIp").toString();
            //客户端类型： AOS、IOS、PC、WINPHONE、WEB、REST，字符串类型
//            String clientType = jsStr.get("clientType").toString();
            //当前sdk的版本信息，字符串类型
//            String sdkVersion = jsStr.get("sdkVersion").toString();
            User user = userInfoDao.getUserInfoById(Long.parseLong(accid));
            if(user!=null && user.getIsHost()==1){
                logger.info("lineTimeRabbitMQ用户为主播，忽略该次同步,accid::::::"+accid
                            +",eventType::::::"+eventType);
                return;
            }
            lineTimeService.countLineTime(eventType,accid,timestamp,user);
        } catch (Exception ex) {
            logger.error("lineTimeRabbitMQ处理错误,json---{},type---{}", json, type);
            logger.error("lineTimeRabbitMQ处理错误ex", ex);
        }
    }
}
